import {
	config
} from "@/utils/config";

// 例外不用token的地址
var exceptionAddrArr = [
	"https://api.weixin.qq.com/cv/ocr/idcard",
];
//请求头处理函数
function createHeader(url) {
	let header = {
		// "content-type": "application/json"
	};
	if (exceptionAddrArr.indexOf(url) == -1) {
		//排除请求的地址不须要token的地址
		let token = uni.getStorageSync('token');
		header.Authorization = token;
	}
	return header;
}
/**
 * 该方法实现请求的统一处理
 */
function commonhandle(resData) {
	console.log(resData, 'resData---')
	uni.showToast({
		title: resData.msg,
		icon: "none"
	})
	let codes = [401];
	console.log(resData, 'resData')
	if (codes.includes(resData.code)) {
		let pages = getCurrentPages() // 获取栈实例
		let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
		if (currentRoute !== 'pages/login/index') {
			uni.reLaunch({
				url: '/pages/login/login'
			});
		}
		//清除缓存
		uni.setStorageSync('token', '');
	}
}
export default class request {
	// 发起 GET 请求
	get(url, data) {
		let header = createHeader(url);
		let serverUrl = config.baseUrl;
		return new Promise((resolve, reject) => {
			uni.request({
				url: serverUrl + url,
				data,
				method: 'GET',
				header: header,
				success: (res) => {
					if (url === '/pvms/wx/getWXAccessToken') {
						resolve(res.data);
					} else {
						if (res.data.code == 200 || res.data.code == 1) {
							resolve(res.data);
						} else {
							commonhandle(res.data)
							reject(res.data);
						}
					}

				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	}
	// 发起 POST 请求
	post(url, data) {
		let header = createHeader(url);
		let serverUrl = config.baseUrl;
		return new Promise((resolve, reject) => {
			uni.request({
				url: serverUrl + url,
				data,
				method: 'POST',
				header: header,
				success: (res) => {
					if (res.data.code == 200 || res.data.code == 1) {
						resolve(res.data);
					} else {
						commonhandle(res.data)
						reject(res.data);
					}
				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	}
	// 调第三方接口
	postOther(url, data) {
		let header = createHeader(url);
		return new Promise((resolve, reject) => {
			uni.request({
				url: config.wxApi + url,
				data,
				method: 'POST',
				success: (res) => {
					console.log(res, 'res--')
					resolve(res.data);
				},
				fail: (err) => {
					reject(err);
				},
			});
		});
	}
}